#! /bin/bash

function help(){
	echo "
		使用方法：regularLog  filename  mvpathname
			filename：需要移动的文件名称
			mvpathname：移动到的文件路径
		eg:  regularLog /home/file1  /home/files -- 移动 /home/file1  到 /home/files下
	
	"
}


last_arg_index=""
last_arg=""
## 参数判断
function checkParam(){
	if [ $# -lt 2 ]
	then
        	help
        	exit 1
	fi
	
	
	if [ $? != 0 ]; then
		echo "执行参数检查1失败!!!"
		exit -1
	fi
	
	if [ ! -e "$1" ] ||  [ ! -f  "$1"  ]; then 
		echo "路径名错误!(不是文件或者文件不存在)"
		exit -1
	fi
	
	if [ $? != 0 ]; then
		echo "执行参数检查2失败!!!"
		exit -1
	fi
	
	## 获取最后一个参数
	last_arg_index=$(( $# ))
	last_arg=${@:$last_arg_index:1}

	if [ ! -e "$last_arg" ] || [ ! -d "$last_arg" ]; then
		echo "移动路径名错误!（非目录或者目录不存在）"
		exit -1
	fi

	
	if [ $? != 0 ]; then
		echo "执行参数检查3失败!!!"
		exit -1
	fi
}

## 循环参数处理
function handle(){
	## 移动目标路径
	mvpath="$1"

	#for arg in "${@:2:$#-1}"; do
	for ((index=2;index < $#;index++));do
		echo ${!index}
		basepath=$(dirname "${!index}")
		filename=$(basename "${!index}")
		file="${!index}"
		fileSwap="$basepath/.$filename.swp" 

		## 判断是否在被使用
		if ! fuser $file &> /dev/null  ; then
			if [ -f "$fileSwap" ]; then
				echo "$file is using(swp)!!!"
				exit -1
			else	
				mv $file  $mvpath
				if [ $? == 0 ] ; then
					echo "mv $file to $mvpath success"
				else
					echo "mv $file failed"
					exit -1
				fi
			fi
		else
			echo "$file is using!!!"
			exit -1
		fi
	done
}

## 函数调用
checkParam $@

if [ $? != 0 ]; then
	echo "执行参数检查失败!!!"
	exit -1
fi

if [ -z "$last_arg" ]; then
	echo "目标路径参数获取错误"
	exit -1;
fi

if [ $? != 0 ]; then
	echo "执行参数检查2失败!!!"
	exit -1
fi

## 处理函数
handle "$last_arg" $@
